package cn.edu.glut.choosethesis.controller;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.assertj.core.util.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.glut.choosethesis.service.SubjectService;
import cn.edu.glut.dto.Response;
import cn.edu.glut.dto.SubjectInputDTO;
import cn.edu.glut.dto.UserIntro;
import cn.edu.glut.entity.Subject;
import cn.edu.glut.entity.Teacher;
import cn.edu.glut.user.service.UserDetailService;
import cn.edu.glut.utils.ExcelUtils;
import cn.edu.glut.vo.SubjectToTeacherVO;
import lombok.Cleanup;

@RestController
@RequestMapping("/subject")
public class SubjectController {
	
	@Autowired
	SubjectService subjectService;

	//根据session来进行插入
	@RequestMapping("/new")
	public Response save(@Valid SubjectInputDTO subjectInputDTO, HttpSession session){
		Preconditions.checkNotNull(subjectInputDTO.getOffer(), "供选人数不能为空");
		UserIntro u = (UserIntro) session.getAttribute("user");
		if(null!=u && u.getUserType()==UserDetailService.TYPE_TEACHER){
			subjectInputDTO.setTeacherId(u.getId());
			return Response.success(subjectService.save(subjectInputDTO.convertToEntity()));
		}
		return Response.success(0);
	}
	
	@RequestMapping("/del/{id}")
	public Response delete(@PathVariable String id){
		subjectService.delete(id);
		return Response.success();
	}
	
	@RequestMapping("/dels")
	public Response delete(){
		subjectService.deleteAll();
		return Response.success();
	}
	
	@RequestMapping("/update")
	public Response update(@Valid SubjectInputDTO subjectInputDTO,HttpSession session){
		Preconditions.checkNotNull(subjectInputDTO.getId(), "题目id不能为空");
		UserIntro u = (UserIntro) session.getAttribute("user");
		if(null!=u && u.getUserType()==UserDetailService.TYPE_TEACHER){
			return Response.success(subjectService.update(subjectInputDTO.convertToEntity()));
		}
		return Response.success(0);
	}
	
	@RequestMapping("/get/{id}")
	public Response get(@PathVariable String id){
		Subject s = subjectService.findById(id);
		if(null != s)
			s.getTeacher().setPassword(null);
		return Response.success(s);
	}
	
	/**
	 * 传参即为条件过滤
	 * @param isSelect 是否选题
	 * @param titleLike 题目标题
	 * @param teacherId 根据老师筛选
	 */
	@RequestMapping("/export")
	public Response export(Boolean isSelect, String titleLike, String teacherId, HttpServletResponse response) throws Exception{
		List<SubjectToTeacherVO> voList = subjectService.list(null, isSelect, titleLike, teacherId, null, null).getContent();
		if(voList==null || voList.size()==0)
			return Response.success("目前还没有数据");
		String fileName = "选题信息总览.xls";
		response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("utf-8"),"iso-8859-1"));//解决乱码
		response.setContentType("application/octet-stream;charset=UTF-8");
		@Cleanup OutputStream out = response.getOutputStream();
		ExcelUtils.<SubjectToTeacherVO>exportExcel(SubjectToTeacherVO.getExcelCellKey(), voList, out);
		return Response.success();
	}
	
	/**
	 * 该方法需要根据session信息分辨显示某老师的题目还是全部题目
	 * @param pageable	分页信息
	 * @param isSelect	是否确选
	 * @param titleLike	模糊标题查询
	 * @param teacherId 当学生查看某老师的所有题目时，该参数必传
	 * @param majorId 	当session为秘书或者admin时,查询的是某专业下的题目状态
	 * @param studentId 与session为student相同作用，但是仅对admin开放传值
	 * @return
	 */
	@RequestMapping("/list")
	public Response list(@PageableDefault Pageable pageable, Boolean isSelect, String titleLike, String teacherId,
			String majorId, String studentId, HttpServletRequest req) {
		HttpSession session = req.getSession();
		UserIntro user = (UserIntro) session.getAttribute("user");
		// 根据session类型进行选择返回
		if(null!=user && user.getUserType() == UserDetailService.TYPE_TEACHER)
			return Response.success(subjectService.list(pageable, isSelect, titleLike, user.getId(), null, null));
		//如果是学生查询，需要查询该学生所属专业的题目（在sql中子查询查出专业id）
		if(null!=user && user.getUserType() == UserDetailService.TYPE_STUDENT)
			return Response.success(subjectService.list(pageable, isSelect, titleLike, teacherId, null, user.getId()));
		return Response.success(subjectService.list(pageable, isSelect, titleLike, teacherId, majorId, studentId));
	}
	
}
